home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / logging / __init__.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  50.1 KB  |  1,568 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """
  5. Logging package for Python. Based on PEP 282 and comments thereto in
  6. comp.lang.python, and influenced by Apache's log4j system.
  7.  
  8. Copyright (C) 2001-2009 Vinay Sajip. All Rights Reserved.
  9.  
  10. To use, simply 'import logging' and log away!
  11. """
  12. __all__ = [
  13.     'BASIC_FORMAT',
  14.     'BufferingFormatter',
  15.     'CRITICAL',
  16.     'DEBUG',
  17.     'ERROR',
  18.     'FATAL',
  19.     'FileHandler',
  20.     'Filter',
  21.     'Filterer',
  22.     'Formatter',
  23.     'Handler',
  24.     'INFO',
  25.     'LogRecord',
  26.     'Logger',
  27.     'Manager',
  28.     'NOTSET',
  29.     'PlaceHolder',
  30.     'RootLogger',
  31.     'StreamHandler',
  32.     'WARN',
  33.     'WARNING']
  34. import sys
  35. import os
  36. import types
  37. import time
  38. import string
  39. import cStringIO
  40. import traceback
  41.  
  42. try:
  43.     import codecs
  44. except ImportError:
  45.     codecs = None
  46.  
  47.  
  48. try:
  49.     import thread
  50.     import threading
  51. except ImportError:
  52.     thread = None
  53.  
  54. __author__ = 'Vinay Sajip <vinay_sajip@red-dove.com>'
  55. __status__ = 'production'
  56. __version__ = '0.5.0.5'
  57. __date__ = '17 February 2009'
  58. if hasattr(sys, 'frozen'):
  59.     _srcfile = 'logging%s__init__%s' % (os.sep, __file__[-4:])
  60. elif string.lower(__file__[-4:]) in ('.pyc', '.pyo'):
  61.     _srcfile = __file__[:-4] + '.py'
  62. else:
  63.     _srcfile = __file__
  64. _srcfile = os.path.normcase(_srcfile)
  65.  
  66. def currentframe():
  67.     """Return the frame object for the caller's stack frame."""
  68.     
  69.     try:
  70.         raise Exception
  71.     except:
  72.         return sys.exc_traceback.tb_frame.f_back
  73.  
  74.  
  75. if hasattr(sys, '_getframe'):
  76.     
  77.     currentframe = lambda : sys._getframe(3)
  78.  
  79. _startTime = time.time()
  80. raiseExceptions = 1
  81. logThreads = 1
  82. logMultiprocessing = 1
  83. logProcesses = 1
  84. CRITICAL = 50
  85. FATAL = CRITICAL
  86. ERROR = 40
  87. WARNING = 30
  88. WARN = WARNING
  89. INFO = 20
  90. DEBUG = 10
  91. NOTSET = 0
  92. _levelNames = {
  93.     CRITICAL: 'CRITICAL',
  94.     ERROR: 'ERROR',
  95.     WARNING: 'WARNING',
  96.     INFO: 'INFO',
  97.     DEBUG: 'DEBUG',
  98.     NOTSET: 'NOTSET',
  99.     'CRITICAL': CRITICAL,
  100.     'ERROR': ERROR,
  101.     'WARN': WARNING,
  102.     'WARNING': WARNING,
  103.     'INFO': INFO,
  104.     'DEBUG': DEBUG,
  105.     'NOTSET': NOTSET }
  106.  
  107. def getLevelName(level):
  108.     '''
  109.     Return the textual representation of logging level \'level\'.
  110.  
  111.     If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
  112.     INFO, DEBUG) then you get the corresponding string. If you have
  113.     associated levels with names using addLevelName then the name you have
  114.     associated with \'level\' is returned.
  115.  
  116.     If a numeric value corresponding to one of the defined levels is passed
  117.     in, the corresponding string representation is returned.
  118.  
  119.     Otherwise, the string "Level %s" % level is returned.
  120.     '''
  121.     return _levelNames.get(level, 'Level %s' % level)
  122.  
  123.  
  124. def addLevelName(level, levelName):
  125.     """
  126.     Associate 'levelName' with 'level'.
  127.  
  128.     This is used when converting levels to text during message formatting.
  129.     """
  130.     _acquireLock()
  131.     
  132.     try:
  133.         _levelNames[level] = levelName
  134.         _levelNames[levelName] = level
  135.     finally:
  136.         _releaseLock()
  137.  
  138.  
  139. _lock = None
  140.  
  141. def _acquireLock():
  142.     '''
  143.     Acquire the module-level lock for serializing access to shared data.
  144.  
  145.     This should be released with _releaseLock().
  146.     '''
  147.     global _lock
  148.     if not _lock and thread:
  149.         _lock = threading.RLock()
  150.     
  151.     if _lock:
  152.         _lock.acquire()
  153.     
  154.  
  155.  
  156. def _releaseLock():
  157.     '''
  158.     Release the module-level lock acquired by calling _acquireLock().
  159.     '''
  160.     if _lock:
  161.         _lock.release()
  162.     
  163.  
  164.  
  165. class LogRecord:
  166.     '''
  167.     A LogRecord instance represents an event being logged.
  168.  
  169.     LogRecord instances are created every time something is logged. They
  170.     contain all the information pertinent to the event being logged. The
  171.     main information passed in is in msg and args, which are combined
  172.     using str(msg) % args to create the message field of the record. The
  173.     record also includes information such as when the record was created,
  174.     the source line where the logging call was made, and any exception
  175.     information to be logged.
  176.     '''
  177.     
  178.     def __init__(self, name, level, pathname, lineno, msg, args, exc_info, func = None):
  179.         '''
  180.         Initialize a logging record with interesting information.
  181.         '''
  182.         ct = time.time()
  183.         self.name = name
  184.         self.msg = msg
  185.         if args and len(args) == 1 and type(args[0]) == types.DictType and args[0]:
  186.             args = args[0]
  187.         
  188.         self.args = args
  189.         self.levelname = getLevelName(level)
  190.         self.levelno = level
  191.         self.pathname = pathname
  192.         
  193.         try:
  194.             self.filename = os.path.basename(pathname)
  195.             self.module = os.path.splitext(self.filename)[0]
  196.         except (TypeError, ValueError, AttributeError):
  197.             self.filename = pathname
  198.             self.module = 'Unknown module'
  199.  
  200.         self.exc_info = exc_info
  201.         self.exc_text = None
  202.         self.lineno = lineno
  203.         self.funcName = func
  204.         self.created = ct
  205.         self.msecs = (ct - long(ct)) * 1000
  206.         self.relativeCreated = (self.created - _startTime) * 1000
  207.         if logThreads and thread:
  208.             self.thread = thread.get_ident()
  209.             self.threadName = threading.current_thread().name
  210.         else:
  211.             self.thread = None
  212.             self.threadName = None
  213.         if logMultiprocessing:
  214.             current_process = current_process
  215.             import multiprocessing
  216.             self.processName = current_process().name
  217.         else:
  218.             self.processName = None
  219.         if logProcesses and hasattr(os, 'getpid'):
  220.             self.process = os.getpid()
  221.         else:
  222.             self.process = None
  223.  
  224.     
  225.     def __str__(self):
  226.         return '<LogRecord: %s, %s, %s, %s, "%s">' % (self.name, self.levelno, self.pathname, self.lineno, self.msg)
  227.  
  228.     
  229.     def getMessage(self):
  230.         '''
  231.         Return the message for this LogRecord.
  232.  
  233.         Return the message for this LogRecord after merging any user-supplied
  234.         arguments with the message.
  235.         '''
  236.         if not hasattr(types, 'UnicodeType'):
  237.             msg = str(self.msg)
  238.         else:
  239.             msg = self.msg
  240.             if type(msg) not in (types.UnicodeType, types.StringType):
  241.                 
  242.                 try:
  243.                     msg = str(self.msg)
  244.                 except UnicodeError:
  245.                     msg = self.msg
  246.                 except:
  247.                     None<EXCEPTION MATCH>UnicodeError
  248.                 
  249.  
  250.             None<EXCEPTION MATCH>UnicodeError
  251.         if self.args:
  252.             msg = msg % self.args
  253.         
  254.         return msg
  255.  
  256.  
  257.  
  258. def makeLogRecord(dict):
  259.     '''
  260.     Make a LogRecord whose attributes are defined by the specified dictionary,
  261.     This function is useful for converting a logging event received over
  262.     a socket connection (which is sent as a dictionary) into a LogRecord
  263.     instance.
  264.     '''
  265.     rv = LogRecord(None, None, '', 0, '', (), None, None)
  266.     rv.__dict__.update(dict)
  267.     return rv
  268.  
  269.  
  270. class Formatter:
  271.     '''
  272.     Formatter instances are used to convert a LogRecord to text.
  273.  
  274.     Formatters need to know how a LogRecord is constructed. They are
  275.     responsible for converting a LogRecord to (usually) a string which can
  276.     be interpreted by either a human or an external system. The base Formatter
  277.     allows a formatting string to be specified. If none is supplied, the
  278.     default value of "%s(message)\\n" is used.
  279.  
  280.     The Formatter can be initialized with a format string which makes use of
  281.     knowledge of the LogRecord attributes - e.g. the default value mentioned
  282.     above makes use of the fact that the user\'s message and arguments are pre-
  283.     formatted into a LogRecord\'s message attribute. Currently, the useful
  284.     attributes in a LogRecord are described by:
  285.  
  286.     %(name)s            Name of the logger (logging channel)
  287.     %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
  288.                         WARNING, ERROR, CRITICAL)
  289.     %(levelname)s       Text logging level for the message ("DEBUG", "INFO",
  290.                         "WARNING", "ERROR", "CRITICAL")
  291.     %(pathname)s        Full pathname of the source file where the logging
  292.                         call was issued (if available)
  293.     %(filename)s        Filename portion of pathname
  294.     %(module)s          Module (name portion of filename)
  295.     %(lineno)d          Source line number where the logging call was issued
  296.                         (if available)
  297.     %(funcName)s        Function name
  298.     %(created)f         Time when the LogRecord was created (time.time()
  299.                         return value)
  300.     %(asctime)s         Textual time when the LogRecord was created
  301.     %(msecs)d           Millisecond portion of the creation time
  302.     %(relativeCreated)d Time in milliseconds when the LogRecord was created,
  303.                         relative to the time the logging module was loaded
  304.                         (typically at application startup time)
  305.     %(thread)d          Thread ID (if available)
  306.     %(threadName)s      Thread name (if available)
  307.     %(process)d         Process ID (if available)
  308.     %(message)s         The result of record.getMessage(), computed just as
  309.                         the record is emitted
  310.     '''
  311.     converter = time.localtime
  312.     
  313.     def __init__(self, fmt = None, datefmt = None):
  314.         '''
  315.         Initialize the formatter with specified format strings.
  316.  
  317.         Initialize the formatter either with the specified format string, or a
  318.         default as described above. Allow for specialized date formatting with
  319.         the optional datefmt argument (if omitted, you get the ISO8601 format).
  320.         '''
  321.         if fmt:
  322.             self._fmt = fmt
  323.         else:
  324.             self._fmt = '%(message)s'
  325.         self.datefmt = datefmt
  326.  
  327.     
  328.     def formatTime(self, record, datefmt = None):
  329.         """
  330.         Return the creation time of the specified LogRecord as formatted text.
  331.  
  332.         This method should be called from format() by a formatter which
  333.         wants to make use of a formatted time. This method can be overridden
  334.         in formatters to provide for any specific requirement, but the
  335.         basic behaviour is as follows: if datefmt (a string) is specified,
  336.         it is used with time.strftime() to format the creation time of the
  337.         record. Otherwise, the ISO8601 format is used. The resulting
  338.         string is returned. This function uses a user-configurable function
  339.         to convert the creation time to a tuple. By default, time.localtime()
  340.         is used; to change this for a particular formatter instance, set the
  341.         'converter' attribute to a function with the same signature as
  342.         time.localtime() or time.gmtime(). To change it for all formatters,
  343.         for example if you want all logging times to be shown in GMT,
  344.         set the 'converter' attribute in the Formatter class.
  345.         """
  346.         ct = self.converter(record.created)
  347.         if datefmt:
  348.             s = time.strftime(datefmt, ct)
  349.         else:
  350.             t = time.strftime('%Y-%m-%d %H:%M:%S', ct)
  351.             s = '%s,%03d' % (t, record.msecs)
  352.         return s
  353.  
  354.     
  355.     def formatException(self, ei):
  356.         '''
  357.         Format and return the specified exception information as a string.
  358.  
  359.         This default implementation just uses
  360.         traceback.print_exception()
  361.         '''
  362.         sio = cStringIO.StringIO()
  363.         traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
  364.         s = sio.getvalue()
  365.         sio.close()
  366.         if s[-1:] == '\n':
  367.             s = s[:-1]
  368.         
  369.         return s
  370.  
  371.     
  372.     def format(self, record):
  373.         '''
  374.         Format the specified record as text.
  375.  
  376.         The record\'s attribute dictionary is used as the operand to a
  377.         string formatting operation which yields the returned string.
  378.         Before formatting the dictionary, a couple of preparatory steps
  379.         are carried out. The message attribute of the record is computed
  380.         using LogRecord.getMessage(). If the formatting string contains
  381.         "%(asctime)", formatTime() is called to format the event time.
  382.         If there is exception information, it is formatted using
  383.         formatException() and appended to the message.
  384.         '''
  385.         record.message = record.getMessage()
  386.         if string.find(self._fmt, '%(asctime)') >= 0:
  387.             record.asctime = self.formatTime(record, self.datefmt)
  388.         
  389.         s = self._fmt % record.__dict__
  390.         if record.exc_info:
  391.             if not record.exc_text:
  392.                 record.exc_text = self.formatException(record.exc_info)
  393.             
  394.         
  395.         if record.exc_text:
  396.             if s[-1:] != '\n':
  397.                 s = s + '\n'
  398.             
  399.             s = s + record.exc_text
  400.         
  401.         return s
  402.  
  403.  
  404. _defaultFormatter = Formatter()
  405.  
  406. class BufferingFormatter:
  407.     '''
  408.     A formatter suitable for formatting a number of records.
  409.     '''
  410.     
  411.     def __init__(self, linefmt = None):
  412.         '''
  413.         Optionally specify a formatter which will be used to format each
  414.         individual record.
  415.         '''
  416.         if linefmt:
  417.             self.linefmt = linefmt
  418.         else:
  419.             self.linefmt = _defaultFormatter
  420.  
  421.     
  422.     def formatHeader(self, records):
  423.         '''
  424.         Return the header string for the specified records.
  425.         '''
  426.         return ''
  427.  
  428.     
  429.     def formatFooter(self, records):
  430.         '''
  431.         Return the footer string for the specified records.
  432.         '''
  433.         return ''
  434.  
  435.     
  436.     def format(self, records):
  437.         '''
  438.         Format the specified records and return the result as a string.
  439.         '''
  440.         rv = ''
  441.         if len(records) > 0:
  442.             rv = rv + self.formatHeader(records)
  443.             for record in records:
  444.                 rv = rv + self.linefmt.format(record)
  445.             
  446.             rv = rv + self.formatFooter(records)
  447.         
  448.         return rv
  449.  
  450.  
  451.  
  452. class Filter:
  453.     '''
  454.     Filter instances are used to perform arbitrary filtering of LogRecords.
  455.  
  456.     Loggers and Handlers can optionally use Filter instances to filter
  457.     records as desired. The base filter class only allows events which are
  458.     below a certain point in the logger hierarchy. For example, a filter
  459.     initialized with "A.B" will allow events logged by loggers "A.B",
  460.     "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
  461.     initialized with the empty string, all events are passed.
  462.     '''
  463.     
  464.     def __init__(self, name = ''):
  465.         '''
  466.         Initialize a filter.
  467.  
  468.         Initialize with the name of the logger which, together with its
  469.         children, will have its events allowed through the filter. If no
  470.         name is specified, allow every event.
  471.         '''
  472.         self.name = name
  473.         self.nlen = len(name)
  474.  
  475.     
  476.     def filter(self, record):
  477.         '''
  478.         Determine if the specified record is to be logged.
  479.  
  480.         Is the specified record to be logged? Returns 0 for no, nonzero for
  481.         yes. If deemed appropriate, the record may be modified in-place.
  482.         '''
  483.         if self.nlen == 0:
  484.             return 1
  485.         if self.name == record.name:
  486.             return 1
  487.         if string.find(record.name, self.name, 0, self.nlen) != 0:
  488.             return 0
  489.         return record.name[self.nlen] == '.'
  490.  
  491.  
  492.  
  493. class Filterer:
  494.     '''
  495.     A base class for loggers and handlers which allows them to share
  496.     common code.
  497.     '''
  498.     
  499.     def __init__(self):
  500.         '''
  501.         Initialize the list of filters to be an empty list.
  502.         '''
  503.         self.filters = []
  504.  
  505.     
  506.     def addFilter(self, filter):
  507.         '''
  508.         Add the specified filter to this handler.
  509.         '''
  510.         if filter not in self.filters:
  511.             self.filters.append(filter)
  512.         
  513.  
  514.     
  515.     def removeFilter(self, filter):
  516.         '''
  517.         Remove the specified filter from this handler.
  518.         '''
  519.         if filter in self.filters:
  520.             self.filters.remove(filter)
  521.         
  522.  
  523.     
  524.     def filter(self, record):
  525.         '''
  526.         Determine if a record is loggable by consulting all the filters.
  527.  
  528.         The default is to allow the record to be logged; any filter can veto
  529.         this and the record is then dropped. Returns a zero value if a record
  530.         is to be dropped, else non-zero.
  531.         '''
  532.         rv = 1
  533.         for f in self.filters:
  534.             if not f.filter(record):
  535.                 rv = 0
  536.                 break
  537.                 continue
  538.         
  539.         return rv
  540.  
  541.  
  542. _handlers = { }
  543. _handlerList = []
  544.  
  545. class Handler(Filterer):
  546.     """
  547.     Handler instances dispatch logging events to specific destinations.
  548.  
  549.     The base handler class. Acts as a placeholder which defines the Handler
  550.     interface. Handlers can optionally use Formatter instances to format
  551.     records as desired. By default, no formatter is specified; in this case,
  552.     the 'raw' message as determined by record.message is logged.
  553.     """
  554.     
  555.     def __init__(self, level = NOTSET):
  556.         '''
  557.         Initializes the instance - basically setting the formatter to None
  558.         and the filter list to empty.
  559.         '''
  560.         Filterer.__init__(self)
  561.         self.level = level
  562.         self.formatter = None
  563.         _acquireLock()
  564.         
  565.         try:
  566.             _handlers[self] = 1
  567.             _handlerList.insert(0, self)
  568.         finally:
  569.             _releaseLock()
  570.  
  571.         self.createLock()
  572.  
  573.     
  574.     def createLock(self):
  575.         '''
  576.         Acquire a thread lock for serializing access to the underlying I/O.
  577.         '''
  578.         if thread:
  579.             self.lock = threading.RLock()
  580.         else:
  581.             self.lock = None
  582.  
  583.     
  584.     def acquire(self):
  585.         '''
  586.         Acquire the I/O thread lock.
  587.         '''
  588.         if self.lock:
  589.             self.lock.acquire()
  590.         
  591.  
  592.     
  593.     def release(self):
  594.         '''
  595.         Release the I/O thread lock.
  596.         '''
  597.         if self.lock:
  598.             self.lock.release()
  599.         
  600.  
  601.     
  602.     def setLevel(self, level):
  603.         '''
  604.         Set the logging level of this handler.
  605.         '''
  606.         self.level = level
  607.  
  608.     
  609.     def format(self, record):
  610.         '''
  611.         Format the specified record.
  612.  
  613.         If a formatter is set, use it. Otherwise, use the default formatter
  614.         for the module.
  615.         '''
  616.         if self.formatter:
  617.             fmt = self.formatter
  618.         else:
  619.             fmt = _defaultFormatter
  620.         return fmt.format(record)
  621.  
  622.     
  623.     def emit(self, record):
  624.         '''
  625.         Do whatever it takes to actually log the specified logging record.
  626.  
  627.         This version is intended to be implemented by subclasses and so
  628.         raises a NotImplementedError.
  629.         '''
  630.         raise NotImplementedError, 'emit must be implemented by Handler subclasses'
  631.  
  632.     
  633.     def handle(self, record):
  634.         '''
  635.         Conditionally emit the specified logging record.
  636.  
  637.         Emission depends on filters which may have been added to the handler.
  638.         Wrap the actual emission of the record with acquisition/release of
  639.         the I/O thread lock. Returns whether the filter passed the record for
  640.         emission.
  641.         '''
  642.         rv = self.filter(record)
  643.         if rv:
  644.             self.acquire()
  645.             
  646.             try:
  647.                 self.emit(record)
  648.             finally:
  649.                 self.release()
  650.  
  651.         
  652.         return rv
  653.  
  654.     
  655.     def setFormatter(self, fmt):
  656.         '''
  657.         Set the formatter for this handler.
  658.         '''
  659.         self.formatter = fmt
  660.  
  661.     
  662.     def flush(self):
  663.         '''
  664.         Ensure all logging output has been flushed.
  665.  
  666.         This version does nothing and is intended to be implemented by
  667.         subclasses.
  668.         '''
  669.         pass
  670.  
  671.     
  672.     def close(self):
  673.         '''
  674.         Tidy up any resources used by the handler.
  675.  
  676.         This version does removes the handler from an internal list
  677.         of handlers which is closed when shutdown() is called. Subclasses
  678.         should ensure that this gets called from overridden close()
  679.         methods.
  680.         '''
  681.         _acquireLock()
  682.         
  683.         try:
  684.             del _handlers[self]
  685.             _handlerList.remove(self)
  686.         finally:
  687.             _releaseLock()
  688.  
  689.  
  690.     
  691.     def handleError(self, record):
  692.         '''
  693.         Handle errors which occur during an emit() call.
  694.  
  695.         This method should be called from handlers when an exception is
  696.         encountered during an emit() call. If raiseExceptions is false,
  697.         exceptions get silently ignored. This is what is mostly wanted
  698.         for a logging system - most users will not care about errors in
  699.         the logging system, they are more interested in application errors.
  700.         You could, however, replace this with a custom handler if you wish.
  701.         The record which was being processed is passed in to this method.
  702.         '''
  703.         if raiseExceptions:
  704.             ei = sys.exc_info()
  705.             traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
  706.             del ei
  707.         
  708.  
  709.  
  710.  
  711. class StreamHandler(Handler):
  712.     '''
  713.     A handler class which writes logging records, appropriately formatted,
  714.     to a stream. Note that this class does not close the stream, as
  715.     sys.stdout or sys.stderr may be used.
  716.     '''
  717.     
  718.     def __init__(self, strm = None):
  719.         '''
  720.         Initialize the handler.
  721.  
  722.         If strm is not specified, sys.stderr is used.
  723.         '''
  724.         Handler.__init__(self)
  725.         if strm is None:
  726.             strm = sys.stderr
  727.         
  728.         self.stream = strm
  729.  
  730.     
  731.     def flush(self):
  732.         '''
  733.         Flushes the stream.
  734.         '''
  735.         if self.stream and hasattr(self.stream, 'flush'):
  736.             self.stream.flush()
  737.         
  738.  
  739.     
  740.     def emit(self, record):
  741.         """
  742.         Emit a record.
  743.  
  744.         If a formatter is specified, it is used to format the record.
  745.         The record is then written to the stream with a trailing newline.  If
  746.         exception information is present, it is formatted using
  747.         traceback.print_exception and appended to the stream.  If the stream
  748.         has an 'encoding' attribute, it is used to encode the message before
  749.         output to the stream.
  750.         """
  751.         
  752.         try:
  753.             msg = self.format(record)
  754.             stream = self.stream
  755.             fs = '%s\n'
  756.             if not hasattr(types, 'UnicodeType'):
  757.                 stream.write(fs % msg)
  758.             else:
  759.                 
  760.                 try:
  761.                     if isinstance(msg, unicode) or getattr(stream, 'encoding', None) is None:
  762.                         stream.write(fs % msg)
  763.                     else:
  764.                         stream.write(fs % msg.encode(stream.encoding))
  765.                 except UnicodeError:
  766.                     stream.write(fs % msg.encode('UTF-8'))
  767.  
  768.             self.flush()
  769.         except (KeyboardInterrupt, SystemExit):
  770.             raise 
  771.         except:
  772.             self.handleError(record)
  773.  
  774.  
  775.  
  776.  
  777. class FileHandler(StreamHandler):
  778.     '''
  779.     A handler class which writes formatted logging records to disk files.
  780.     '''
  781.     
  782.     def __init__(self, filename, mode = 'a', encoding = None, delay = 0):
  783.         '''
  784.         Open the specified file and use it as the stream for logging.
  785.         '''
  786.         if codecs is None:
  787.             encoding = None
  788.         
  789.         self.baseFilename = os.path.abspath(filename)
  790.         self.mode = mode
  791.         self.encoding = encoding
  792.         if delay:
  793.             Handler.__init__(self)
  794.             self.stream = None
  795.         else:
  796.             StreamHandler.__init__(self, self._open())
  797.  
  798.     
  799.     def close(self):
  800.         '''
  801.         Closes the stream.
  802.         '''
  803.         if self.stream:
  804.             self.flush()
  805.             if hasattr(self.stream, 'close'):
  806.                 self.stream.close()
  807.             
  808.             StreamHandler.close(self)
  809.             self.stream = None
  810.         
  811.  
  812.     
  813.     def _open(self):
  814.         '''
  815.         Open the current base file with the (original) mode and encoding.
  816.         Return the resulting stream.
  817.         '''
  818.         if self.encoding is None:
  819.             stream = open(self.baseFilename, self.mode)
  820.         else:
  821.             stream = codecs.open(self.baseFilename, self.mode, self.encoding)
  822.         return stream
  823.  
  824.     
  825.     def emit(self, record):
  826.         """
  827.         Emit a record.
  828.  
  829.         If the stream was not opened because 'delay' was specified in the
  830.         constructor, open it before calling the superclass's emit.
  831.         """
  832.         if self.stream is None:
  833.             self.stream = self._open()
  834.         
  835.         StreamHandler.emit(self, record)
  836.  
  837.  
  838.  
  839. class PlaceHolder:
  840.     '''
  841.     PlaceHolder instances are used in the Manager logger hierarchy to take
  842.     the place of nodes for which no loggers have been defined. This class is
  843.     intended for internal use only and not as part of the public API.
  844.     '''
  845.     
  846.     def __init__(self, alogger):
  847.         '''
  848.         Initialize with the specified logger being a child of this placeholder.
  849.         '''
  850.         self.loggerMap = {
  851.             alogger: None }
  852.  
  853.     
  854.     def append(self, alogger):
  855.         '''
  856.         Add the specified logger as a child of this placeholder.
  857.         '''
  858.         if alogger not in self.loggerMap:
  859.             self.loggerMap[alogger] = None
  860.         
  861.  
  862.  
  863. _loggerClass = None
  864.  
  865. def setLoggerClass(klass):
  866.     '''
  867.     Set the class to be used when instantiating a logger. The class should
  868.     define __init__() such that only a name argument is required, and the
  869.     __init__() should call Logger.__init__()
  870.     '''
  871.     global _loggerClass
  872.     if klass != Logger:
  873.         if not issubclass(klass, Logger):
  874.             raise TypeError, 'logger not derived from logging.Logger: ' + klass.__name__
  875.         issubclass(klass, Logger)
  876.     
  877.     _loggerClass = klass
  878.  
  879.  
  880. def getLoggerClass():
  881.     '''
  882.     Return the class to be used when instantiating a logger.
  883.     '''
  884.     return _loggerClass
  885.  
  886.  
  887. class Manager:
  888.     '''
  889.     There is [under normal circumstances] just one Manager instance, which
  890.     holds the hierarchy of loggers.
  891.     '''
  892.     
  893.     def __init__(self, rootnode):
  894.         '''
  895.         Initialize the manager with the root node of the logger hierarchy.
  896.         '''
  897.         self.root = rootnode
  898.         self.disable = 0
  899.         self.emittedNoHandlerWarning = 0
  900.         self.loggerDict = { }
  901.  
  902.     
  903.     def getLogger(self, name):
  904.         '''
  905.         Get a logger with the specified name (channel name), creating it
  906.         if it doesn\'t yet exist. This name is a dot-separated hierarchical
  907.         name, such as "a", "a.b", "a.b.c" or similar.
  908.  
  909.         If a PlaceHolder existed for the specified name [i.e. the logger
  910.         didn\'t exist but a child of it did], replace it with the created
  911.         logger and fix up the parent/child references which pointed to the
  912.         placeholder to now point to the logger.
  913.         '''
  914.         rv = None
  915.         _acquireLock()
  916.         
  917.         try:
  918.             if name in self.loggerDict:
  919.                 rv = self.loggerDict[name]
  920.                 if isinstance(rv, PlaceHolder):
  921.                     ph = rv
  922.                     rv = _loggerClass(name)
  923.                     rv.manager = self
  924.                     self.loggerDict[name] = rv
  925.                     self._fixupChildren(ph, rv)
  926.                     self._fixupParents(rv)
  927.                 
  928.             else:
  929.                 rv = _loggerClass(name)
  930.                 rv.manager = self
  931.                 self.loggerDict[name] = rv
  932.                 self._fixupParents(rv)
  933.         finally:
  934.             _releaseLock()
  935.  
  936.         return rv
  937.  
  938.     
  939.     def _fixupParents(self, alogger):
  940.         '''
  941.         Ensure that there are either loggers or placeholders all the way
  942.         from the specified logger to the root of the logger hierarchy.
  943.         '''
  944.         name = alogger.name
  945.         i = string.rfind(name, '.')
  946.         rv = None
  947.         while i > 0 and not rv:
  948.             substr = name[:i]
  949.             if substr not in self.loggerDict:
  950.                 self.loggerDict[substr] = PlaceHolder(alogger)
  951.             else:
  952.                 obj = self.loggerDict[substr]
  953.                 if isinstance(obj, Logger):
  954.                     rv = obj
  955.                 elif not isinstance(obj, PlaceHolder):
  956.                     raise AssertionError
  957.                 obj.append(alogger)
  958.             i = string.rfind(name, '.', 0, i - 1)
  959.         if not rv:
  960.             rv = self.root
  961.         
  962.         alogger.parent = rv
  963.  
  964.     
  965.     def _fixupChildren(self, ph, alogger):
  966.         '''
  967.         Ensure that children of the placeholder ph are connected to the
  968.         specified logger.
  969.         '''
  970.         name = alogger.name
  971.         namelen = len(name)
  972.         for c in ph.loggerMap.keys():
  973.             if c.parent.name[:namelen] != name:
  974.                 alogger.parent = c.parent
  975.                 c.parent = alogger
  976.                 continue
  977.         
  978.  
  979.  
  980.  
  981. class Logger(Filterer):
  982.     '''
  983.     Instances of the Logger class represent a single logging channel. A
  984.     "logging channel" indicates an area of an application. Exactly how an
  985.     "area" is defined is up to the application developer. Since an
  986.     application can have any number of areas, logging channels are identified
  987.     by a unique string. Application areas can be nested (e.g. an area
  988.     of "input processing" might include sub-areas "read CSV files", "read
  989.     XLS files" and "read Gnumeric files"). To cater for this natural nesting,
  990.     channel names are organized into a namespace hierarchy where levels are
  991.     separated by periods, much like the Java or Python package namespace. So
  992.     in the instance given above, channel names might be "input" for the upper
  993.     level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
  994.     There is no arbitrary limit to the depth of nesting.
  995.     '''
  996.     
  997.     def __init__(self, name, level = NOTSET):
  998.         '''
  999.         Initialize the logger with a name and an optional level.
  1000.         '''
  1001.         Filterer.__init__(self)
  1002.         self.name = name
  1003.         self.level = level
  1004.         self.parent = None
  1005.         self.propagate = 1
  1006.         self.handlers = []
  1007.         self.disabled = 0
  1008.  
  1009.     
  1010.     def setLevel(self, level):
  1011.         '''
  1012.         Set the logging level of this logger.
  1013.         '''
  1014.         self.level = level
  1015.  
  1016.     
  1017.     def debug(self, msg, *args, **kwargs):
  1018.         '''
  1019.         Log \'msg % args\' with severity \'DEBUG\'.
  1020.  
  1021.         To pass exception information, use the keyword argument exc_info with
  1022.         a true value, e.g.
  1023.  
  1024.         logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
  1025.         '''
  1026.         if self.isEnabledFor(DEBUG):
  1027.             self._log(DEBUG, msg, args, **kwargs)
  1028.         
  1029.  
  1030.     
  1031.     def info(self, msg, *args, **kwargs):
  1032.         '''
  1033.         Log \'msg % args\' with severity \'INFO\'.
  1034.  
  1035.         To pass exception information, use the keyword argument exc_info with
  1036.         a true value, e.g.
  1037.  
  1038.         logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
  1039.         '''
  1040.         if self.isEnabledFor(INFO):
  1041.             self._log(INFO, msg, args, **kwargs)
  1042.         
  1043.  
  1044.     
  1045.     def warning(self, msg, *args, **kwargs):
  1046.         '''
  1047.         Log \'msg % args\' with severity \'WARNING\'.
  1048.  
  1049.         To pass exception information, use the keyword argument exc_info with
  1050.         a true value, e.g.
  1051.  
  1052.         logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
  1053.         '''
  1054.         if self.isEnabledFor(WARNING):
  1055.             self._log(WARNING, msg, args, **kwargs)
  1056.         
  1057.  
  1058.     warn = warning
  1059.     
  1060.     def error(self, msg, *args, **kwargs):
  1061.         '''
  1062.         Log \'msg % args\' with severity \'ERROR\'.
  1063.  
  1064.         To pass exception information, use the keyword argument exc_info with
  1065.         a true value, e.g.
  1066.  
  1067.         logger.error("Houston, we have a %s", "major problem", exc_info=1)
  1068.         '''
  1069.         if self.isEnabledFor(ERROR):
  1070.             self._log(ERROR, msg, args, **kwargs)
  1071.         
  1072.  
  1073.     
  1074.     def exception(self, msg, *args):
  1075.         '''
  1076.         Convenience method for logging an ERROR with exception information.
  1077.         '''
  1078.         self.error(*(msg,) + args, **{
  1079.             'exc_info': 1 })
  1080.  
  1081.     
  1082.     def critical(self, msg, *args, **kwargs):
  1083.         '''
  1084.         Log \'msg % args\' with severity \'CRITICAL\'.
  1085.  
  1086.         To pass exception information, use the keyword argument exc_info with
  1087.         a true value, e.g.
  1088.  
  1089.         logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
  1090.         '''
  1091.         if self.isEnabledFor(CRITICAL):
  1092.             self._log(CRITICAL, msg, args, **kwargs)
  1093.         
  1094.  
  1095.     fatal = critical
  1096.     
  1097.     def log(self, level, msg, *args, **kwargs):
  1098.         '''
  1099.         Log \'msg % args\' with the integer severity \'level\'.
  1100.  
  1101.         To pass exception information, use the keyword argument exc_info with
  1102.         a true value, e.g.
  1103.  
  1104.         logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
  1105.         '''
  1106.         if type(level) != types.IntType:
  1107.             if raiseExceptions:
  1108.                 raise TypeError, 'level must be an integer'
  1109.             raiseExceptions
  1110.             return None
  1111.         type(level) != types.IntType
  1112.         if self.isEnabledFor(level):
  1113.             self._log(level, msg, args, **kwargs)
  1114.         
  1115.  
  1116.     
  1117.     def findCaller(self):
  1118.         '''
  1119.         Find the stack frame of the caller so that we can note the source
  1120.         file name, line number and function name.
  1121.         '''
  1122.         f = currentframe().f_back
  1123.         rv = ('(unknown file)', 0, '(unknown function)')
  1124.         while hasattr(f, 'f_code'):
  1125.             co = f.f_code
  1126.             filename = os.path.normcase(co.co_filename)
  1127.             if filename == _srcfile:
  1128.                 f = f.f_back
  1129.                 continue
  1130.             
  1131.             rv = (filename, f.f_lineno, co.co_name)
  1132.             break
  1133.         return rv
  1134.  
  1135.     
  1136.     def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func = None, extra = None):
  1137.         '''
  1138.         A factory method which can be overridden in subclasses to create
  1139.         specialized LogRecords.
  1140.         '''
  1141.         rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
  1142.         if extra is not None:
  1143.             for key in extra:
  1144.                 if key in ('message', 'asctime') or key in rv.__dict__:
  1145.                     raise KeyError('Attempt to overwrite %r in LogRecord' % key)
  1146.                 key in rv.__dict__
  1147.                 rv.__dict__[key] = extra[key]
  1148.             
  1149.         
  1150.         return rv
  1151.  
  1152.     
  1153.     def _log(self, level, msg, args, exc_info = None, extra = None):
  1154.         '''
  1155.         Low-level logging routine which creates a LogRecord and then calls
  1156.         all the handlers of this logger to handle the record.
  1157.         '''
  1158.         if _srcfile:
  1159.             
  1160.             try:
  1161.                 (fn, lno, func) = self.findCaller()
  1162.             except ValueError:
  1163.                 (fn, lno, func) = ('(unknown file)', 0, '(unknown function)')
  1164.             except:
  1165.                 None<EXCEPTION MATCH>ValueError
  1166.             
  1167.  
  1168.         None<EXCEPTION MATCH>ValueError
  1169.         (fn, lno, func) = ('(unknown file)', 0, '(unknown function)')
  1170.         if exc_info:
  1171.             if type(exc_info) != types.TupleType:
  1172.                 exc_info = sys.exc_info()
  1173.             
  1174.         
  1175.         record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
  1176.         self.handle(record)
  1177.  
  1178.     
  1179.     def handle(self, record):
  1180.         '''
  1181.         Call the handlers for the specified record.
  1182.  
  1183.         This method is used for unpickled records received from a socket, as
  1184.         well as those created locally. Logger-level filtering is applied.
  1185.         '''
  1186.         if not (self.disabled) and self.filter(record):
  1187.             self.callHandlers(record)
  1188.         
  1189.  
  1190.     
  1191.     def addHandler(self, hdlr):
  1192.         '''
  1193.         Add the specified handler to this logger.
  1194.         '''
  1195.         if hdlr not in self.handlers:
  1196.             self.handlers.append(hdlr)
  1197.         
  1198.  
  1199.     
  1200.     def removeHandler(self, hdlr):
  1201.         '''
  1202.         Remove the specified handler from this logger.
  1203.         '''
  1204.         if hdlr in self.handlers:
  1205.             hdlr.acquire()
  1206.             
  1207.             try:
  1208.                 self.handlers.remove(hdlr)
  1209.             finally:
  1210.                 hdlr.release()
  1211.  
  1212.         
  1213.  
  1214.     
  1215.     def callHandlers(self, record):
  1216.         '''
  1217.         Pass a record to all relevant handlers.
  1218.  
  1219.         Loop through all handlers for this logger and its parents in the
  1220.         logger hierarchy. If no handler was found, output a one-off error
  1221.         message to sys.stderr. Stop searching up the hierarchy whenever a
  1222.         logger with the "propagate" attribute set to zero is found - that
  1223.         will be the last logger whose handlers are called.
  1224.         '''
  1225.         c = self
  1226.         found = 0
  1227.         while c:
  1228.             for hdlr in c.handlers:
  1229.                 found = found + 1
  1230.                 if record.levelno >= hdlr.level:
  1231.                     hdlr.handle(record)
  1232.                     continue
  1233.             
  1234.             if not c.propagate:
  1235.                 c = None
  1236.                 continue
  1237.             c = c.parent
  1238.         if found == 0 and raiseExceptions and not (self.manager.emittedNoHandlerWarning):
  1239.             sys.stderr.write('No handlers could be found for logger "%s"\n' % self.name)
  1240.             self.manager.emittedNoHandlerWarning = 1
  1241.         
  1242.  
  1243.     
  1244.     def getEffectiveLevel(self):
  1245.         '''
  1246.         Get the effective level for this logger.
  1247.  
  1248.         Loop through this logger and its parents in the logger hierarchy,
  1249.         looking for a non-zero logging level. Return the first one found.
  1250.         '''
  1251.         logger = self
  1252.         while logger:
  1253.             if logger.level:
  1254.                 return logger.level
  1255.             logger = logger.parent
  1256.             continue
  1257.             logger.level
  1258.         return NOTSET
  1259.  
  1260.     
  1261.     def isEnabledFor(self, level):
  1262.         """
  1263.         Is this logger enabled for level 'level'?
  1264.         """
  1265.         if self.manager.disable >= level:
  1266.             return 0
  1267.         return level >= self.getEffectiveLevel()
  1268.  
  1269.  
  1270.  
  1271. class RootLogger(Logger):
  1272.     '''
  1273.     A root logger is not that different to any other logger, except that
  1274.     it must have a logging level and there is only one instance of it in
  1275.     the hierarchy.
  1276.     '''
  1277.     
  1278.     def __init__(self, level):
  1279.         '''
  1280.         Initialize the logger with the name "root".
  1281.         '''
  1282.         Logger.__init__(self, 'root', level)
  1283.  
  1284.  
  1285. _loggerClass = Logger
  1286.  
  1287. class LoggerAdapter:
  1288.     '''
  1289.     An adapter for loggers which makes it easier to specify contextual
  1290.     information in logging output.
  1291.     '''
  1292.     
  1293.     def __init__(self, logger, extra):
  1294.         '''
  1295.         Initialize the adapter with a logger and a dict-like object which
  1296.         provides contextual information. This constructor signature allows
  1297.         easy stacking of LoggerAdapters, if so desired.
  1298.  
  1299.         You can effectively pass keyword arguments as shown in the
  1300.         following example:
  1301.  
  1302.         adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
  1303.         '''
  1304.         self.logger = logger
  1305.         self.extra = extra
  1306.  
  1307.     
  1308.     def process(self, msg, kwargs):
  1309.         """
  1310.         Process the logging message and keyword arguments passed in to
  1311.         a logging call to insert contextual information. You can either
  1312.         manipulate the message itself, the keyword args or both. Return
  1313.         the message and kwargs modified (or not) to suit your needs.
  1314.  
  1315.         Normally, you'll only need to override this one method in a
  1316.         LoggerAdapter subclass for your specific needs.
  1317.         """
  1318.         kwargs['extra'] = self.extra
  1319.         return (msg, kwargs)
  1320.  
  1321.     
  1322.     def debug(self, msg, *args, **kwargs):
  1323.         '''
  1324.         Delegate a debug call to the underlying logger, after adding
  1325.         contextual information from this adapter instance.
  1326.         '''
  1327.         (msg, kwargs) = self.process(msg, kwargs)
  1328.         self.logger.debug(msg, *args, **kwargs)
  1329.  
  1330.     
  1331.     def info(self, msg, *args, **kwargs):
  1332.         '''
  1333.         Delegate an info call to the underlying logger, after adding
  1334.         contextual information from this adapter instance.
  1335.         '''
  1336.         (msg, kwargs) = self.process(msg, kwargs)
  1337.         self.logger.info(msg, *args, **kwargs)
  1338.  
  1339.     
  1340.     def warning(self, msg, *args, **kwargs):
  1341.         '''
  1342.         Delegate a warning call to the underlying logger, after adding
  1343.         contextual information from this adapter instance.
  1344.         '''
  1345.         (msg, kwargs) = self.process(msg, kwargs)
  1346.         self.logger.warning(msg, *args, **kwargs)
  1347.  
  1348.     
  1349.     def error(self, msg, *args, **kwargs):
  1350.         '''
  1351.         Delegate an error call to the underlying logger, after adding
  1352.         contextual information from this adapter instance.
  1353.         '''
  1354.         (msg, kwargs) = self.process(msg, kwargs)
  1355.         self.logger.error(msg, *args, **kwargs)
  1356.  
  1357.     
  1358.     def exception(self, msg, *args, **kwargs):
  1359.         '''
  1360.         Delegate an exception call to the underlying logger, after adding
  1361.         contextual information from this adapter instance.
  1362.         '''
  1363.         (msg, kwargs) = self.process(msg, kwargs)
  1364.         kwargs['exc_info'] = 1
  1365.         self.logger.error(msg, *args, **kwargs)
  1366.  
  1367.     
  1368.     def critical(self, msg, *args, **kwargs):
  1369.         '''
  1370.         Delegate a critical call to the underlying logger, after adding
  1371.         contextual information from this adapter instance.
  1372.         '''
  1373.         (msg, kwargs) = self.process(msg, kwargs)
  1374.         self.logger.critical(msg, *args, **kwargs)
  1375.  
  1376.     
  1377.     def log(self, level, msg, *args, **kwargs):
  1378.         '''
  1379.         Delegate a log call to the underlying logger, after adding
  1380.         contextual information from this adapter instance.
  1381.         '''
  1382.         (msg, kwargs) = self.process(msg, kwargs)
  1383.         self.logger.log(level, msg, *args, **kwargs)
  1384.  
  1385.  
  1386. root = RootLogger(WARNING)
  1387. Logger.root = root
  1388. Logger.manager = Manager(Logger.root)
  1389. BASIC_FORMAT = '%(levelname)s:%(name)s:%(message)s'
  1390.  
  1391. def basicConfig(**kwargs):
  1392.     """
  1393.     Do basic configuration for the logging system.
  1394.  
  1395.     This function does nothing if the root logger already has handlers
  1396.     configured. It is a convenience method intended for use by simple scripts
  1397.     to do one-shot configuration of the logging package.
  1398.  
  1399.     The default behaviour is to create a StreamHandler which writes to
  1400.     sys.stderr, set a formatter using the BASIC_FORMAT format string, and
  1401.     add the handler to the root logger.
  1402.  
  1403.     A number of optional keyword arguments may be specified, which can alter
  1404.     the default behaviour.
  1405.  
  1406.     filename  Specifies that a FileHandler be created, using the specified
  1407.               filename, rather than a StreamHandler.
  1408.     filemode  Specifies the mode to open the file, if filename is specified
  1409.               (if filemode is unspecified, it defaults to 'a').
  1410.     format    Use the specified format string for the handler.
  1411.     datefmt   Use the specified date/time format.
  1412.     level     Set the root logger level to the specified level.
  1413.     stream    Use the specified stream to initialize the StreamHandler. Note
  1414.               that this argument is incompatible with 'filename' - if both
  1415.               are present, 'stream' is ignored.
  1416.  
  1417.     Note that you could specify a stream created using open(filename, mode)
  1418.     rather than passing the filename and mode in. However, it should be
  1419.     remembered that StreamHandler does not close its stream (since it may be
  1420.     using sys.stdout or sys.stderr), whereas FileHandler closes its stream
  1421.     when the handler is closed.
  1422.     """
  1423.     if len(root.handlers) == 0:
  1424.         filename = kwargs.get('filename')
  1425.         if filename:
  1426.             mode = kwargs.get('filemode', 'a')
  1427.             hdlr = FileHandler(filename, mode)
  1428.         else:
  1429.             stream = kwargs.get('stream')
  1430.             hdlr = StreamHandler(stream)
  1431.         fs = kwargs.get('format', BASIC_FORMAT)
  1432.         dfs = kwargs.get('datefmt', None)
  1433.         fmt = Formatter(fs, dfs)
  1434.         hdlr.setFormatter(fmt)
  1435.         root.addHandler(hdlr)
  1436.         level = kwargs.get('level')
  1437.         if level is not None:
  1438.             root.setLevel(level)
  1439.         
  1440.     
  1441.  
  1442.  
  1443. def getLogger(name = None):
  1444.     '''
  1445.     Return a logger with the specified name, creating it if necessary.
  1446.  
  1447.     If no name is specified, return the root logger.
  1448.     '''
  1449.     if name:
  1450.         return Logger.manager.getLogger(name)
  1451.     return root
  1452.  
  1453.  
  1454. def critical(msg, *args, **kwargs):
  1455.     """
  1456.     Log a message with severity 'CRITICAL' on the root logger.
  1457.     """
  1458.     if len(root.handlers) == 0:
  1459.         basicConfig()
  1460.     
  1461.     root.critical(*(msg,) + args, **kwargs)
  1462.  
  1463. fatal = critical
  1464.  
  1465. def error(msg, *args, **kwargs):
  1466.     """
  1467.     Log a message with severity 'ERROR' on the root logger.
  1468.     """
  1469.     if len(root.handlers) == 0:
  1470.         basicConfig()
  1471.     
  1472.     root.error(*(msg,) + args, **kwargs)
  1473.  
  1474.  
  1475. def exception(msg, *args):
  1476.     """
  1477.     Log a message with severity 'ERROR' on the root logger,
  1478.     with exception information.
  1479.     """
  1480.     error(*(msg,) + args, **{
  1481.         'exc_info': 1 })
  1482.  
  1483.  
  1484. def warning(msg, *args, **kwargs):
  1485.     """
  1486.     Log a message with severity 'WARNING' on the root logger.
  1487.     """
  1488.     if len(root.handlers) == 0:
  1489.         basicConfig()
  1490.     
  1491.     root.warning(*(msg,) + args, **kwargs)
  1492.  
  1493. warn = warning
  1494.  
  1495. def info(msg, *args, **kwargs):
  1496.     """
  1497.     Log a message with severity 'INFO' on the root logger.
  1498.     """
  1499.     if len(root.handlers) == 0:
  1500.         basicConfig()
  1501.     
  1502.     root.info(*(msg,) + args, **kwargs)
  1503.  
  1504.  
  1505. def debug(msg, *args, **kwargs):
  1506.     """
  1507.     Log a message with severity 'DEBUG' on the root logger.
  1508.     """
  1509.     if len(root.handlers) == 0:
  1510.         basicConfig()
  1511.     
  1512.     root.debug(*(msg,) + args, **kwargs)
  1513.  
  1514.  
  1515. def log(level, msg, *args, **kwargs):
  1516.     """
  1517.     Log 'msg % args' with the integer severity 'level' on the root logger.
  1518.     """
  1519.     if len(root.handlers) == 0:
  1520.         basicConfig()
  1521.     
  1522.     root.log(*(level, msg) + args, **kwargs)
  1523.  
  1524.  
  1525. def disable(level):
  1526.     """
  1527.     Disable all logging calls less severe than 'level'.
  1528.     """
  1529.     root.manager.disable = level
  1530.  
  1531.  
  1532. def shutdown(handlerList = _handlerList):
  1533.     '''
  1534.     Perform any cleanup actions in the logging system (e.g. flushing
  1535.     buffers).
  1536.  
  1537.     Should be called at application exit.
  1538.     '''
  1539.     for h in handlerList[:]:
  1540.         
  1541.         try:
  1542.             h.flush()
  1543.             h.close()
  1544.         continue
  1545.         if raiseExceptions:
  1546.             raise 
  1547.         raiseExceptions
  1548.         continue
  1549.  
  1550.     
  1551.  
  1552.  
  1553. try:
  1554.     import atexit
  1555.     atexit.register(shutdown)
  1556. except ImportError:
  1557.     
  1558.     def exithook(status, old_exit = sys.exit):
  1559.         
  1560.         try:
  1561.             shutdown()
  1562.         finally:
  1563.             old_exit(status)
  1564.  
  1565.  
  1566.     sys.exit = exithook
  1567.  
  1568.